package com.industry.oss.controller;

import com.industry.framework.common.Result;
import com.industry.framework.core.generic.AbstractCoreGenericController;
import com.industry.oss.controller.vo.FileUploadInfoVO;
import com.industry.oss.dal.dataobject.Files;
import com.industry.oss.service.FilesService;
import com.industry.oss.controller.vo.UploadUrlsVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author jsy
 * @description:文件上传下载
 * @date 2025/5/12 11:19
 */
@RestController
@RequestMapping("/files")
@Slf4j
public class FilesController extends AbstractCoreGenericController<Files, String> {

    @Resource
    private FilesService filesService;

    /**
     * @description: 检查文件是否存在
     * @author: jsy
     * @time: 2025/5/12 11:20
     */
    @GetMapping("/multipart/check/{md5}")
    public Result<FileUploadInfoVO> checkFileByMd5(@PathVariable("md5") String md5) {
        log.info("查询 <{}> 文件是否存在、是否进行断点续传", md5);
        return filesService.checkFileByMd5(md5);
    }

    /**
     * @description: 初始化文件分片地址及相关数据
     * @author: jsy
     * @time: 2025/5/12 11:20
     */
    @PostMapping("/multipart/init")
    public Result<UploadUrlsVO> initMultiPartUpload(@RequestBody FileUploadInfoVO fileUploadInfoVO) {
        log.info("通过 <{}> 初始化上传任务", fileUploadInfoVO);
        return filesService.initMultipartUpload(fileUploadInfoVO);
    }

    /**
     * @description: 文件合并（单文件不会合并，仅信息入库）
     * @author: jsy
     * @time: 2025/5/12 11:20
     */
    @PostMapping("/multipart/merge/{md5}")
    public Result<String> mergeMultipartUpload(@PathVariable("md5") String md5) {
        log.info("通过 <{}> 合并上传任务", md5);
        return filesService.mergeMultipartUpload(md5);
    }

   /**
    * @description: 下载文件（分片）
    * @author: jsy
    * @time: 2025/5/12 11:20
    */
    @GetMapping("/download/{id}")
    public Result<byte[]> downloadMultipartFile(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("通过 <{}> 开始分片下载", id);
        return filesService.downloadMultipartFile(id, request, response);
    }

    @GetMapping("/list")
    public Result<List<Files>> getFileList() {
        return Result.success(filesService.getFileList());
    }
}
